import React, { useState, useEffect } from 'react';
import { Form, DatePicker, Input, Select, Spin, Row, Col } from 'antd';
import PropTypes from 'prop-types';
import moment from 'moment';
import FileUpload from '@/components/Custom/FileUpload';
import { useEmployeeList, useDictionary, useQuitNotice, useAttachment, renderFiles } from '../utils';

const { Item } = Form;
const { TextArea } = Input;
const { Option } = Select;

// 员工基本信息
const Originator = ({ isEdit, form, relatedBusinessObject, otherPost, leaveOfficeId, currentUser }) => {
    const { getFieldDecorator } = form;
    const {
        employeeName,
        applyLeaveDate,
        actualLeaveDate,
        leaveReasonTypeName,
        leaveDesc,
        quitNoticeName
    } = relatedBusinessObject;
    const [params, setParams] = useState({
        companyId: currentUser.companyId,
        departmentId: otherPost ? '' : currentUser.departmentId
    });
    const { file = {} } = useAttachment(leaveOfficeId);
    const { leaveOfficeFile = [] } = file;
    const [selectedUser, setSelectedUser] = useState({});
    const { loading, employeeList } = useEmployeeList(params);
    const { loading: noticeLoading, dictionary: noticeList } = useDictionary({
        code: 'probationQuitNoticeType'
    });
    const { loading: leaveTypeLoading, dictionary: leaveReasons } = useDictionary({
        code: 'reasonType'
    });
    const [reasonMain, setReasonMain] = useState({});
    const { loading: leaveSubTypeLoading, dictionary: leaveSubReasons } = useDictionary({
        code: reasonMain && reasonMain.remark
    });
    const { quitNotice: {
        regularQuitNotice,
        probationQuitNotice,
        inServiceStatus
    } } = useQuitNotice(otherPost ? selectedUser.userCode : currentUser.userCode);
    const fileList = [];

    const files = leaveOfficeFile || [];
    files.forEach(item => {
        const { originName, url, keyName } = item;
        const fileObj = {
            keyName,
            name: originName,
            url,
            uid: keyName
        };
        fileList.push(fileObj);
    });

    const handleEmployeeSelect = employeeId => {
        const find = employeeList.find(item => item.id === employeeId);

        if (find) {
            setSelectedUser(find);
            form.setFieldsValue({
                employeeName: find.employeeName,
                companyId: find.companyId,
                companyName: find.companyName,
                departmentId: find.departmentId,
                departmentName: find.departmentName,
                postId: find.postId,
                postName: find.postName,
                userNo: find.userNo
            });
        }
    };
    const handleEmployeeSearch = text => {
        setParams({
            ...params,
            userName: text
        });
    };
    const employeeNameMsg = !leaveOfficeId ? currentUser.employeeName : employeeName;
    let quitNoticeInit = '';
    if (inServiceStatus === '') {
        quitNoticeInit = 'one_month';
    } else if (inServiceStatus === '1') {
        quitNoticeInit = regularQuitNotice || 'one_month';
    } else {
        quitNoticeInit = probationQuitNotice || 'one_month';
    }
    const notice = form.getFieldValue('quitNotice');
    const date = form.getFieldValue('applyLeaveDate');
    const reasonTypeVal = form.getFieldValue('reasonType');

    useEffect(() => {
        let resultDate = null;
        if (!date || !notice) {
            form.setFieldsValue({
                actualLeaveDate: null
            });
            return;
        }
        if (notice === 'one_week') {
            resultDate = date.clone().add(1, 'w').subtract(1, 'd');
        } else if (notice === 'two_week') {
            resultDate = date.clone().add(2, 'w').subtract(1, 'd');
        } else if (notice === 'one_month') {
            resultDate = date.clone().add(1, 'M').subtract(1, 'd');
        } else if (notice === 'two_month') {
            resultDate = date.clone().add(2, 'M').subtract(1, 'd');
        }
        form.setFieldsValue({
            actualLeaveDate: resultDate
        });
    }, [notice, date ? date.format('YYYY-MM-DD') : null]);
    useEffect(() => {
        if (reasonTypeVal) {
            setReasonMain(leaveReasons.find(item => item.dictValue === reasonTypeVal));
        }
    }, [reasonTypeVal, leaveReasons]);
    return (
        <div>
            <h3>{!otherPost && !leaveOfficeId ? '员工基本信息' : '离职基本信息'}</h3>
            <Item label="员工姓名" required={isEdit && otherPost}>
                {isEdit && otherPost ? getFieldDecorator('employeeId', {
                    initialValue: relatedBusinessObject.employeeId,
                    rules: [
                        {
                            required: true,
                            message: '请输入员工姓名！'
                        }
                    ]
                })(
                    <Select
                        notFoundContent={loading ? <Spin size="small" /> : null}
                        loading={loading}
                        showSearch
                        onChange={handleEmployeeSelect}
                        placeholder="请输入"
                        showArrow={false}
                        filterOption={false}
                        onSearch={handleEmployeeSearch}
                    >
                        {employeeList.map(item => (
                            <Option key={item.id} value={item.id}>{item.employeeName}</Option>
                        ))}
                    </Select>
                ) : employeeNameMsg}
                {!otherPost && !leaveOfficeId && getFieldDecorator('employeeId', {
                    initialValue: currentUser.id
                })}
                {!leaveOfficeId && getFieldDecorator('employeeName', {
                    initialValue: otherPost ? '' : currentUser.employeeName
                })}
                {!leaveOfficeId && getFieldDecorator('companyName', {
                    initialValue: otherPost ? '' : currentUser.companyName
                })}
                {!leaveOfficeId && getFieldDecorator('companyId', {
                    initialValue: otherPost ? '' : currentUser.companyId
                })}
                {!leaveOfficeId && getFieldDecorator('departmentId', {
                    initialValue: otherPost ? '' : currentUser.departmentId
                })}
                {!leaveOfficeId && getFieldDecorator('departmentName', {
                    initialValue: otherPost ? '' : currentUser.departmentName
                })}
                {!leaveOfficeId && getFieldDecorator('postId', {
                    initialValue: otherPost ? '' : currentUser.postId
                })}
                {!leaveOfficeId && getFieldDecorator('postName', {
                    initialValue: otherPost ? '' : currentUser.postName
                })}
                {isEdit && getFieldDecorator('userNo', {})}
            </Item>
            <Item label="申请离职日期" required={isEdit}>
                {isEdit ? getFieldDecorator('applyLeaveDate', {
                    initialValue: relatedBusinessObject.applyLeaveDate ? moment(relatedBusinessObject.applyLeaveDate)
                        : moment(),
                    rules: [
                        {
                            required: true,
                            message: '请选择申请离职日期！'
                        }
                    ]
                })(
                    <DatePicker style={{ width: '100%' }} />
                ) : (applyLeaveDate || '')}
            </Item>
            <Item label="离职通知期">
                {isEdit ? getFieldDecorator('quitNotice', {
                    initialValue: !leaveOfficeId ? quitNoticeInit : relatedBusinessObject.quitNotice,
                    rules: [
                        {
                            required: true,
                            message: '请选择离职通知期！'
                        }
                    ]
                })(
                    <Select loading={noticeLoading} placeholder="请选择">
                        {noticeList.map(item => (
                            <Option key={item.dictValue} value={item.dictValue}>{item.dictName}</Option>
                        ))}
                    </Select>
                ) : (quitNoticeName || '')}
            </Item>
            <Item label="实际离职时间" required={isEdit && !otherPost}>
                {isEdit ? getFieldDecorator('actualLeaveDate', {
                    rules: [
                        {
                            required: true,
                            message: '请选择实际离职时间！'
                        }
                    ]
                })(
                    <DatePicker style={{ width: '100%' }} disabled />
                ) : (actualLeaveDate || '')}
            </Item>
            <Item style={isEdit ? { marginBottom: 0 } : {}} label="离职原因" required={isEdit}>
                {isEdit && (
                    <Row gutter={8}>
                        <Col span={12}>
                            <Item>
                                {getFieldDecorator('reasonType', {
                                    initialValue: relatedBusinessObject.reasonType,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择离职原因！'
                                        }
                                    ]
                                })(
                                    <Select
                                        onChange={() => {
                                            form.setFieldsValue({
                                                leaveReasonType: undefined
                                            });
                                        }}
                                        loading={leaveTypeLoading}
                                        placeholder="请选择"
                                    >
                                        {leaveReasons.map(reason => (
                                            <Option
                                                key={reason.dictValue}
                                                value={reason.dictValue}
                                            >
                                                {reason.dictName}
                                            </Option>
                                        ))}
                                    </Select>
                                )}
                            </Item>
                        </Col>
                        <Col span={12}>
                            <Item>
                                {getFieldDecorator('leaveReasonType', {
                                    initialValue: typeof relatedBusinessObject.leaveReasonType !== 'undefined' && `${relatedBusinessObject.leaveReasonType}`,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择离职原因！'
                                        }
                                    ]
                                })(
                                    <Select placeholder="请选择" loading={leaveSubTypeLoading}>
                                        {leaveSubReasons.map(reason => (
                                            <Option
                                                key={reason.dictValue}
                                                value={reason.dictValue}
                                            >
                                                {reason.dictName}
                                            </Option>
                                        ))}
                                    </Select>
                                )}
                            </Item>
                        </Col>
                    </Row>
                )}
                {!isEdit && (leaveReasonTypeName || '')}
            </Item>
            <Item label="离职备注" help={isEdit && '0-200个字符'}>
                {isEdit ? getFieldDecorator('leaveDesc', {
                    initialValue: relatedBusinessObject.leaveDesc,
                    rules: [
                        {
                            max: 200,
                            message: '0-200个字符'
                        }
                    ]
                })(
                    <TextArea rows={4} placeholder="请输入" />
                ) : (leaveDesc || '无')}
            </Item>
            <Item label="附件" extra={isEdit && <span style={{ wordBreak: 'break-all' }}>只能上传JPG,JPEG,BMP,GIF,PNG,DOC,DOCX,ppt,pptx,PDF,xls,xlsx,RAR,ZIP,txt,ai格式的文件！</span>}>
                {isEdit && getFieldDecorator('resourceRelation', {
                    initialValue: {
                        allFileList: fileList,
                        uploadResourceFile: null
                    }
                })(
                    <FileUpload
                        businessCode="GmsProcess"
                        categoryCode="leaveOfficeFile"
                    />
                )}
                {!isEdit && renderFiles(leaveOfficeFile)}
            </Item>
        </div>
    )
};

Originator.propTypes = {
    // 是否是HR发起
    otherPost: PropTypes.bool.isRequired,
    isEdit: PropTypes.bool.isRequired,
    form: PropTypes.object.isRequired,
    relatedBusinessObject: PropTypes.object.isRequired
};

export default Originator;
